package cn.cjx.basic.interceptors;

import cn.cjx.basic.annotation.PreAuthorize;
import cn.cjx.basic.domain.LoginData;
import cn.cjx.basic.utils.JwtUtils;
import cn.cjx.basic.utils.Payload;
import cn.cjx.basic.utils.RsaUtils;
import cn.cjx.system.mapper.PermissionMapper;
import cn.cjx.user.domain.Logininfo;
import cn.cjx.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

/**
 * @author: cjx
 * @Date: 2022/5/12
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//从请求头request header中获取token
		String token = request.getHeader("U-TOKEN");
		response.setContentType("application/json;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		//如果不为空则放行
		if (!StringUtils.isEmpty(token)) {
			//使用公钥解密
			PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
			Payload<LoginData> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
			LoginData loginData = (LoginData) payload.getUserInfo();
			Logininfo loginTmp = loginData.getLogininfo();
			if (loginTmp != null) {
				Logininfo logininfo = (Logininfo) loginTmp;
				//判断当前登录人是主站即前台用户，还是后台员工
				if (logininfo.getType() == 1) {
					return true;
				}
					HandlerMethod method = (HandlerMethod) handler;
					PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
					if (preAuthorize == null) {//当前这个方法打了注解，那么就需要校验权限，拥有权限，才能访问
						return true;
					}
					//。获取当前请求的资源
					String sn = preAuthorize.value();
					//。查询出当前登录人所拥有的资源权限
					List<String> permissions = loginData.getPermissions();
				//。比对当前访问的资源是否包含在登录人所拥有的权限中
					if (permissions.contains(sn)) {
						return true;
					}

					//--如果不在 提示没有权限访问，直接返回 {"success":false,"message":"noPermission"}
					PrintWriter writer = response.getWriter();
					writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
					writer.flush();
					writer.close();
					return false;//阻止放行

				}
			}

			//阻止放行，返回登陆失败的信息，提醒前端此时应当跳转到登录页面
			response.setCharacterEncoding("utf-8");
			response.setContentType("application/json;charset = utf-8");
			PrintWriter writer = response.getWriter();
			//返回登录验证信息
			writer.write("{\"success\":false,'resultObj':\"LoginDefault\"}");
			writer.flush();
			writer.close();
			return false;

		}

	}
